package Resurgence

import (
	codecs "sanguo/codec/cs"
	com_attr "sanguo/node/common/attr"
	"sanguo/node/common/com_type"
	"sanguo/node/common/transaction"
	"sanguo/node/node_game"
	"sanguo/node/node_game/module/role"
	"sanguo/node/node_game/user"
	cs_message "sanguo/protocol/cs/message"
	"time"

	"github.com/golang/protobuf/proto"
)

type transactionResurgence struct {
	transaction.TransactionBase
	user    *user.User
	req     *codecs.Message
	resp    *cs_message.ResurgenceToC
	errcode cs_message.EnumType
}

func (this *transactionResurgence) GetModuleName() string {
	return "Resurgence"
}

func (this *transactionResurgence) GetReplyMsg() proto.Message {
	return &cs_message.ResurgenceToC{}
}

func (this *transactionResurgence) SetExpiredTime(expired time.Time) {
	this.Expired = expired
}

func (this *transactionResurgence) GetExpiredTime() time.Time {
	return this.Expired
}

func (this *transactionResurgence) Begin() {
	this.resp = &cs_message.ResurgenceToC{}

	roleModule := this.user.GetModuleByName("role").(*role.RoleModule)
	role := roleModule.CurrentRole()
	if role == nil || !role.IsRoleModleData() {
		node_game.Infoln(role.GetUserID(), "ResurgenceToS : role is nil")
		this.errcode = cs_message.EnumType_ERROR
		this.user.EndTrans(this)
		return
	}
	node_game.Infoln(role.GetUserID(), role.GetID(), "Call Resurgence")
	//判断当前角色是否在进行副本
	instanceZone := role.GetInstanceZone()
	if instanceZone == nil {
		node_game.Infoln(role.GetUserID(), role.GetID(), "ResurgenceToS :instanceZone is nil")
		this.errcode = cs_message.EnumType_ERROR
		this.user.EndTrans(this)
		return
	}

	diamond, _ := role.GetRoleAttr().GetAttr(com_attr.Diamond)
	if instanceZone.InitType == com_type.InstanceZone_YhBattleGround {
		battleGround := role.GetBattleGround()
		if !battleGround.UseFreeResurgenceTimes() {
			diamond -= 10
			if diamond < 0 {
				node_game.Infoln(role.GetUserID(), role.GetID(), "ResurgenceToS : Diamond is not enought")
				this.errcode = cs_message.EnumType_ERROR
				this.user.EndTrans(this)
				return
			}
		}
	}

	role.GetRoleAttr().SetAttr(com_attr.Diamond, diamond)

	node_game.Infoln(role.GetUserID(), role.GetID(), "ResurgenceToS OK")
	this.errcode = cs_message.EnumType_OK
	this.user.EndTrans(this)
}

func (this *transactionResurgence) End() {
	this.resp.Errcode = cs_message.EnumType(this.errcode).Enum()

	this.user.Reply(this.req.GetSeriNo(), this.resp)
}

func (this *transactionResurgence) Timeout() {
	this.errcode = cs_message.EnumType_RETRY
	this.user.EndTrans(this)
}

func init() {
	user.RegisterTransFunc(&cs_message.ResurgenceToS{}, func(user *user.User, msg *codecs.Message) transaction.Transaction {
		return &transactionResurgence{
			user: user,
			req:  msg,
		}
	})
}
